import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

// 路由前置守卫
router.beforeEach((to, form, next) => {
  // 判断有无token,如果有token就不能去首页
  // 如果没有token只能去白名单的页面
  // 白名单
  NProgress.start()
  const whiteList = ['/login', '/404']
  const token = store.state.user.token
  if (token && to.path === '/login') {
    next('/')
    NProgress.done()
  } else if (!token && !whiteList.includes(to.path)) {
    next('/login')
    NProgress.done()
  } else {
    // 获取用户基本信息,如果有没有用户信息并且有token才请求
    if (token && !store.state.user.userInfo.userId) {
      store.dispatch('user/getUserInfo')
    }
    next()
    NProgress.done()
  }
})

router.beforeEach((to, form, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
// 路由后置守卫
router.afterEach((to, form) => {
  NProgress.done()
})
